import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:http/http.dart' as http;

class OnlineHistoryPage extends StatefulWidget {
  const OnlineHistoryPage({super.key});

  @override
  State<OnlineHistoryPage> createState() => _OnlineHistoryPageState();
}

class _OnlineHistoryPageState extends State<OnlineHistoryPage> {
  TextEditingController qrcode = TextEditingController(text: "");
  int pageIndex = 1;
  int pageSize = 4;
  int allCount = 0;
  int allPage = 0;
  List<dynamic> TableArray = [];
  Future<void> getTableValue() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      var res = await http.get(
        Uri.parse(
          "http://${prefs.getString("address")}:${prefs.getString("port")}/api/countLine/alldata?pageIndex=$pageIndex&pageSize=$pageSize&barcode=${qrcode.text}&Line=${prefs.getString("line")}",
        ),
      );
      var count = await http.get(
        Uri.parse(
          "http://${prefs.getString("address")}:${prefs.getString("port")}/api/countLine/alldata?Line=${prefs.getString("line")}",
        ),
      );
      final countResponseJson = json.decode(count.body);
      allCount = countResponseJson["result"].length ?? 0;
      if (allCount > 0) {
        allPage = (allCount / 4).ceil();
      }
      final responseJson = json.decode(res.body);
      setState(() {
        TableArray = responseJson["result"];
      });
    } catch (e) {
      TDToast.showFail("网络请求失败", context: context);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getTableValue();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: EdgeInsets.only(right: 2, left: 2),
        child: Column(
          children: [
            SizedBox(height: 5),
            Row(
              children: [
                SizedBox(
                  height: 40,
                  width: 200,
                  child: TextField(
                    controller: qrcode,
                    keyboardType: TextInputType.none,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: '条码',
                      labelStyle: TextStyle(fontSize: 20),
                    ),
                  ),
                ),
                SizedBox(width: 20),
                TDButton(
                  text: "搜索",
                  style: TDButtonStyle(backgroundColor: Colors.greenAccent),
                  onTap: () {
                    getTableValue();
                  },
                ),
                SizedBox(width: 30,),
                TDButton(
                  text: "清空条码",
                  style: TDButtonStyle(backgroundColor: Colors.white),
                  onTap: () {
                    qrcode.text = "";
                    getTableValue();
                  },
                ),
              ],
            ),
            SizedBox(height: 5),
            TDTable(
              columns: [
                TDTableCol(title: '条码', colKey: 'barCode', ellipsis: true, width: 170),
                TDTableCol(title: '压缩机码1', colKey: 'compressorCode', width: 170),
                TDTableCol(title: '压缩机码2', colKey: 'compressorCode2', width: 170),
                TDTableCol(title: '压缩机码3', colKey: 'compressorCode3', width: 170),
                TDTableCol(title: '压缩机码4', colKey: 'compressorCode4', width: 170),
                TDTableCol(title: '上线时间', colKey: 'onlineTime', width: 170),
              ],
              data: TableArray,
            ),
            SizedBox(height: 5),
            Padding(
              padding: EdgeInsets.only(right: 30),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text("共$allCount条数据 | "),
                  Text("当前页数：$pageIndex 共 $allPage 页 "),
                  TDButton(
                    text: "第一页",
                    onTap: () {
                      if (pageIndex == 1) {
                        TDToast.showText("已是第一页", context: context);
                        return;
                      }
                      pageIndex = 1;
                      getTableValue();
                    },
                  ),
                  Padding(
                    padding: EdgeInsets.only(right: 20, left: 20),
                    child: TDButton(
                      text: "上一页",
                      onTap: () {
                        if (pageIndex <= 1) {
                          TDToast.showFail("已到第一页", context: context);
                          return;
                        }
                        pageIndex -= 1;
                        getTableValue();
                      },
                    ),
                  ),
                  TDButton(
                    text: "下一页",
                    onTap: () {
                      if (TableArray.length != 4) {
                        TDToast.showText("已是最后页数，不能再一下页", context: context);
                        return;
                      }
                      pageIndex += 1;
                      getTableValue();
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
